package com.example.weight.householdWaste;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

public class FacilityRuntimeActivity extends AppCompatActivity {

    private SharedPreferences preferences;

    private ItemAdapter adapter;
    private List<String> nameList;
    private String factory;
    private EditText offReason;

    private TextView onText, offText;

//    private Button onBtn, offBtn;

    private PopupWindow popupWindow;

    private final OkHttpClient client = new OkHttpClient();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_facility_runtime);

        Intent previousIntent = getIntent();
        final String name = previousIntent.getStringExtra("name");
         factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.facility_runtime_titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                FacilityRuntimeActivity.this.finish();
            }

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        // 设置输入记录缓存
        preferences = getSharedPreferences("facility_runtime", Context.MODE_PRIVATE);

        nameList = new ArrayList<>(preferences.getStringSet("offReason", new HashSet<>()));
        List<Item> itemList = new ArrayList<>();

        // Item类型list初始化
        for (String itemName : nameList) {
            itemList.add(new Item(itemName, R.drawable.ic_clear));
        }

        // 创建ListView
        adapter = new ItemAdapter(this, R.layout.adapter_item, itemList);
        ListView listView = new ListView(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            // 若有进行删除操作，更新nameList，否则nameList序号对不上
            if (adapter.getDeletePos() >= 0) {
                List<Item> tempItemList = adapter.getList();
                nameList.clear();
                for (Item item : tempItemList) {
                    nameList.add(item.getName());
                }
            }
            // 根据所选设置输入框文本
            String result = nameList.get(position);
            offReason.setText(result);
            popupWindow.dismiss();
            hideInput();
        });

        // 获取屏幕的宽度并设置popupwindow的宽度为width,这里是根据布局控件所占的权重
        WindowManager wManager = (WindowManager) getSystemService(this.WINDOW_SERVICE);
        int width = wManager.getDefaultDisplay().getWidth() * 3 / 5;
        int height = wManager.getDefaultDisplay().getHeight() / 8;
        // 参数为 1.View 2.宽度 3.高度
        popupWindow = new PopupWindow(listView ,width, WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置点击外部区域可以取消popupWindow
        popupWindow.setOutsideTouchable(true);

        offReason = findViewById(R.id.facility_runtime_off_reason);
        offReason.setOnFocusChangeListener((v, hasFocus) -> {
            // 设置popupWindow显示,并且告诉它显示在那个View下面
            if (hasFocus) {
                // 若聚焦到该输入框，显示下拉列表
                popupWindow.showAsDropDown(offReason);
            }
        });

//        onBtn = findViewById(R.id.facility_runtime_on_btn);
//        offBtn = findViewById(R.id.facility_runtime_off_btn);
        onText = findViewById(R.id.facility_runtime_on_text);
        offText = findViewById(R.id.facility_runtime_off_text);

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/equipmentRunningtime/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
//                                JSONObject data = jsonObject.getJSONObject("data");
//                                String startupTime = data.getString("startupTime");
//                                onText.setText(onText.getText().toString().concat(startupTime));
//                                String shutdownTime = data.getString("shutdownTime");
//                                offReason.setText(data.getString("shutdownReasion"));
//                                offText.setText(offText.getText().toString().concat(shutdownTime.equals("null")?"未填写":shutdownTime));
                                String onRecord = onText.getText().toString();
                                String offRecord = offText.getText().toString();
                                JSONArray data = jsonObject.getJSONArray("data");
                                for (int i = 0; i < data.length(); i++) {
                                    JSONObject item = data.getJSONObject(i);
                                    String startupTime = item.getString("startupTime");
                                    if (!startupTime.equals("null"))
                                        onRecord = onRecord.concat(startupTime+"\n");
                                    String shutdownTime = item.getString("shutdownTime");
                                    if (!shutdownTime.equals("null"))
                                        offRecord = offRecord.concat(shutdownTime+"\n");
                                }
                                onText.setText(onRecord);
                                offText.setText(offRecord);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(FacilityRuntimeActivity.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    public void startUp(View view) {
        new AlertDialog.Builder(FacilityRuntimeActivity.this)
            .setTitle("确定开机吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->{}))
            .setPositiveButton("确定", (dialog, which) -> {
                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/equipmentRunningtime/addStartupTime";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    String code = jsonObject.getString("code");

                                    if (code.startsWith("2")) {
                                        @SuppressLint("SimpleDateFormat")
                                        SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );
                                        String temp = onText.getText().toString();
                                        onText.setText(temp.concat(sdf.format(new Date())+"\n"));

                                        Toast.makeText(FacilityRuntimeActivity.this,
                                                "提交成功", Toast.LENGTH_SHORT).show();
                                    }
                                    else
                                        Toast.makeText(FacilityRuntimeActivity.this,
                                                "提交失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(FacilityRuntimeActivity.this,
                                "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );

                        Map<String, String> map=new HashMap<>();
                        map.put("startupTime", sdf.format(new Date()));
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);

                // 原生OkHttp
//                Date time1 = new Date();
//                new Thread(){
//                    @Override
//                    public void run() {
//                        super.run();
//                        try {
//                            @SuppressLint("SimpleDateFormat")
//                            SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );
//                            RequestBody body = new FormBody.Builder()
//                                    .add("startupTime", sdf.format(new Date()))
//                                    .build();
//                            okhttp3.Request request = new okhttp3.Request.Builder()
//                                    .url(Config.url+"/shlj/equipmentRunningtime/addStartupTime")
//                                    .post(body)
//                                    .build();
//                            okhttp3.Response response = client.newCall(request).execute();
//                            String result = response.body().string();
//                            JSONObject object = new JSONObject(result);
//                            String code = object.getString("code");
//                            Looper.prepare();
//                            if (code.startsWith("2")) {
//                                Date time2 = new Date();
//                                long inter = time2.getTime()-time1.getTime();
//                                Toast.makeText(FacilityRuntimeActivity.this,
//                                        "开机成功 "+inter, Toast.LENGTH_SHORT).show();
//                            } else
//                                Toast.makeText(FacilityRuntimeActivity.this,
//                                        "开机失败", Toast.LENGTH_SHORT).show();
//                            Looper.loop();
//                        } catch (IOException | JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }.start();

                // OkHttp-utils
//                @SuppressLint("SimpleDateFormat")
//                SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );
//                OkHttpUtils.post()
//                        .url(Config.url+"/shlj/equipmentRunningtime/addStartupTime")
//                        .addParams("startupTime", sdf.format(new Date()))
//                        .build()
//                        .execute(new StringCallback() {
//                            @Override
//                            public void onError(Call call, Exception e, int id) {
//                                Toast.makeText(FacilityRuntimeActivity.this,
//                                        "保存失败 "+e.getMessage(), Toast.LENGTH_SHORT).show();
//                            }
//
//                            @Override
//                            public void onResponse(String response, int id) {
//                                try {
//                                    JSONObject jsonObject = new JSONObject(response);
//                                    String code = jsonObject.getString("code");
//                                    if (code.startsWith("2")) {
//                                        Date time2 = new Date();
//                                        long inter = time2.getTime()-time1.getTime();
//                                        Toast.makeText(FacilityRuntimeActivity.this,
//                                                "开机成功 "+inter, Toast.LENGTH_SHORT).show();
//                                    } else
//                                        Toast.makeText(FacilityRuntimeActivity.this,
//                                                "失败", Toast.LENGTH_SHORT).show();
//                                } catch (JSONException e) {
//                                    e.printStackTrace();
//                                }
//                            }
//                        });
            })
            .show();
    }

    public void shutDown(View view) {
        String offReasonStr = offReason.getText().toString();
        if (offReasonStr.equals("")) {
            offReasonStr = "正常关机";
//            Toast.makeText(this, "请填写关机原因", Toast.LENGTH_SHORT).show();
//            return;
        }
        String finalOffReasonStr = offReasonStr;
        new AlertDialog.Builder(this)
            .setTitle("确定保存吗？")
            .setCancelable(false)
            .setNegativeButton("取消", ((dialog, which) ->{}))
            .setPositiveButton("确定", (dialog, which) -> {
                SharedPreferences.Editor editor = preferences.edit();
                // 若有进行删除操作，更新nameList
                List<Item> tempItemList = adapter.getList();
                if (tempItemList.size() != nameList.size()) {
                    nameList.clear();
                    for (Item item : tempItemList) {
                        nameList.add(item.getName());
                    }
                }
                // 判断该输入框内容是否已存在，不存在则加入
                String currentCheckResult = offReason.getText().toString();
                if (!currentCheckResult.equals("") && !nameList.contains(currentCheckResult)) {
                    nameList.add(currentCheckResult);
                }

                editor.putStringSet("offReason", new HashSet<>(nameList));
                editor.apply();

                Date time1 = new Date();

                RequestQueue queue = Volley.newRequestQueue(this);
                String url = Config.url + "/shlj/equipmentRunningtime/addShutdownTime";
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
//                                Log.d("zys", response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
//                                    Log.d("zys", jsonObject.getString("code"));
//                                    Date time2 = new Date();
//                                    long inter = time2.getTime()-time1.getTime();

                                    if (jsonObject.getString("code").startsWith("2")) {
                                        @SuppressLint("SimpleDateFormat")
                                        SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );
                                        String temp = offText.getText().toString();
                                        offText.setText(temp.concat(sdf.format(new Date())+"\n"));

                                        Toast.makeText(FacilityRuntimeActivity.this,
                                                "提交成功", Toast.LENGTH_SHORT).show();
                                    }
                                    else
                                        Toast.makeText(FacilityRuntimeActivity.this,
                                                "失败", Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(FacilityRuntimeActivity.this,
                                "失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );

                        Map<String, String> map=new HashMap<>();
                        map.put("shutdownTime", sdf.format(new Date()));
                        map.put("shutdownReasion", finalOffReasonStr);
                        map.put("factory", factory);
                        return map;
                    }
                };
                stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                queue.add(stringRequest);
            })
            .show();
    }

//    public String post(String url) throws IOException {
//        @SuppressLint("SimpleDateFormat")
//        SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );
//        RequestBody body = new FormBody.Builder()
//                .add("startupTime", sdf.format(new Date()))
//                .build();
//        okhttp3.Request request = new okhttp3.Request.Builder()
//                .url(url)
//                .post(body)
//                .build();
//        okhttp3.Response response = client.newCall(request).execute();
//        return response.body().string();
//    }

//    private void getData() {
//        Date time1 = new Date();

//        new Thread(){
//            @Override
//            public void run() {
//                super.run();
//                try {
//                    @SuppressLint("SimpleDateFormat")
//                    SimpleDateFormat sdf =new SimpleDateFormat("HH:mm" );
//                    RequestBody body = new FormBody.Builder()
//                            .add("startupTime", sdf.format(new Date()))
//                            .build();
//                    okhttp3.Request request = new okhttp3.Request.Builder()
//                            .url(Config.url+"/shlj/equipmentRunningtime/addStartupTime")
//                            .post(body)
//                            .build();
//                    okhttp3.Response response = client.newCall(request).execute();
//                    String result = response.body().string();
//                    JSONObject object = new JSONObject(result);
//                    String code = object.getString("code");
//                    Looper.prepare();
//                    if (code.startsWith("2"))
//                        Toast.makeText(FacilityRuntimeActivity.this,
//                                "保存成功", Toast.LENGTH_SHORT).show();
//                    else
//                        Toast.makeText(FacilityRuntimeActivity.this,
//                                "保存失败", Toast.LENGTH_SHORT).show();
//                    Looper.loop();
//                } catch (IOException | JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();

//        Date timeOn = new Date();
//        Log.d("zys", "on 1 "+timeOn.getTime());
//        Log.d("zys", "on 2 "+time1.getTime());
//        long inter = timeOn.getTime()-time1.getTime();
//        Log.d("zys", inter+" on");
//        Toast.makeText(this, ""+inter, Toast.LENGTH_SHORT).show();
//    }
}
